package com.hearwego;

import java.util.HashMap;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.GpsStatus.NmeaListener;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.hearwego.utilities.Informacion;
import com.hearwego.utilities.RssParserPull;



public class ActivityMapa extends android.support.v4.app.FragmentActivity {
    SharedPreferences preferences;
	SharedPreferences.Editor editor;
	String query, cat_cve;
	private ProgressDialog progressDialog;
	public List<Informacion> resultados, catpoi, caticon;
	public RssParserPull parser;
	String[] arraynombre, arraypoid, arrayicon, arraylat, arraylong, arraydireccion;
	private static GoogleMap mMap;
	private MarkerOptions markeropt = null;
	private HashMap<Marker, EventInfo> eventMarkerMap;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tab_mapa);
		
		
//		mMap = ((MapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
//		mMap = getSupportFragmentManager().findFragmentById(R.id.map);
//		mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

//		mMap = (MapFragment)getFragmentManager().findFragmentById(R.id.map);
//		mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
        preferences= getSharedPreferences("Preferencias",Context.MODE_PRIVATE);
		editor = preferences.edit();
		
		query = preferences.getString("actualquery", getString(R.string.query));
		Log.i("ActualQuery", ""+query);
		
		new LoadMap().execute("");
		
		
	}
	
	public static Marker placeMarker(EventInfo eventInfo) {
		 
		  Marker m  = mMap.addMarker(new MarkerOptions()
		 
		   .position(eventInfo.getCoordinate())
		 
		   .title(eventInfo.getSnippet()));
		 
		  return m;
		 
	}
	
    public class LoadMap extends AsyncTask<String, String, String>{

    	@Override
    	protected void onPreExecute() {
    		super.onPreExecute();
    		Log.i("PRE", "PRE");
    		progressDialog = ProgressDialog.show(ActivityMapa.this, "",
					"Cargando...", true, true, new OnCancelListener() {
						
						@Override
						public void onCancel(DialogInterface arg0) {
							onBackPressed();
						}
			});
    	}
    	
    	
		@Override
		protected String doInBackground(String... params) {
    		Log.i("DO", "DO");

			parser = new RssParserPull(preferences.getString("actualquery", getString(R.string.query)));
			resultados = parser.parse();
			arraynombre = new String[resultados.size()];
			arraypoid = new String[resultados.size()];
			arraylat = new String[resultados.size()];
			arraylong = new String[resultados.size()];
			arraydireccion = new String[resultados.size()];
			arrayicon = new String[resultados.size()];
			
			for(int i=0; i<resultados.size(); i++){
				Log.i("arraynombre", ""+resultados.get(i).getNombre());
				Log.i("arraypoid", ""+resultados.get(i).getId());
				Log.i("arraylat", ""+resultados.get(i).getLat());
				Log.i("arraylong", ""+resultados.get(i).getLng());
				Log.i("arrayicon", ""+resultados.get(i).getIcon());
				Log.i("arraydireccion", ""+resultados.get(i).getDireccion());


				arraynombre[i] = resultados.get(i).getNombre();
				arraypoid[i] = resultados.get(i).getId();
				arraylat[i] = resultados.get(i).getLat();
				arraylong[i] = resultados.get(i).getLng();
				arraydireccion[i] = resultados.get(i).getDireccion();
				parser = new RssParserPull("http://www.smartthinking.com.mx:8080/HearWeGo/DataServlet?" +
						"Query=select+cat_cve+from+pois_categorias+where+poi_idr="+arraypoid[i]+"&BaseDatos=hwg");
				Log.i("cat_eve url", "http://www.smartthinking.com.mx:8080/HearWeGo/DataServlet?" +
						"Query=select+cat_cve+from+pois_categorias+where+poi_idr="+arraypoid[i]+"&BaseDatos=hwg");
				catpoi = parser.parse();
				Log.i("SIZE", catpoi.size()+"");
				cat_cve = catpoi.get(0).getClave();
				Log.i("cat_cve", cat_cve+"");

				parser = new RssParserPull("http://www.smartthinking.com.mx:8080/HearWeGo/DataServlet?" +
						"Query=select+cat_icon+from+categorias+where+cat_cve="+cat_cve+"&BaseDatos=hwg");
				Log.i("cat_icon", "http://www.smartthinking.com.mx:8080/HearWeGo/DataServlet?" +
						"Query=select+cat_icon+from+categorias+where+cat_cve="+cat_cve+"&BaseDatos=hwg");
				caticon = parser.parse();
				if(caticon.size() == 0){
					arrayicon[i] = "1";
				}else{
					arrayicon[i] = caticon.get(0).getIcon();
				}
				
				
			
				
			}
			
			
			return null;
		}
    	
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
    		Log.i("POST", "POST");

			setUpMapIfNeeded();
			
			
			progressDialog.dismiss();
			
		}
    	
    }
    
    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
    		mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

            // Check if we were successful in obtaining the map.
            if (mMap != null) {
            	mMap.setMyLocationEnabled(true);
            	Location loc = mMap.getMyLocation();
//            	// Construct a CameraPosition focusing on Mountain View and animate the camera to that position.
//            	CameraPosition cameraPosition = new CameraPosition.Builder()
//            	    .target(new LatLng(loc.getLatitude(), loc.getLongitude()) )      // Sets the center of the map to Mountain View
//            	    .zoom(17)                   // Sets the zoom
//            	    .bearing(90)                // Sets the orientation of the camera to east
//            	    .tilt(30)                   // Sets the tilt of the camera to 30 degrees
//            	    .build();                   // Creates a CameraPosition from the builder
//            	mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                // The Map is verified. It is now safe to manipulate the map.
            	for(int i = 0; i < resultados.size(); i++){
                	markeropt = new MarkerOptions();

            		int resource = 99;
            		int val; 
            		if(!arrayicon[i].toString().equals("null")){
            			val = Integer.parseInt(arrayicon[i]);
            		}else{
            			val = 99;
            		}
            		switch (val) {
					case 2:
						resource  = R.drawable.poi22x;
						break;
					case 1:
						resource  = R.drawable.poi12x;
						break;
					case 3:
						resource  = R.drawable.poi32x;
						break;
					case 5:
						resource  = R.drawable.poi52x;
						break;
					case 4:
						resource  = R.drawable.poi42x;

						break;
						
					case 6:
						resource  = R.drawable.poi62x;
						break;

					default:
						resource  = R.drawable.poi12x;
						break;
					}
            		if(arraylat[i].toString().equals("null") || arraylong[i].toString().equals("null")){
            			
            		}else{
            			markeropt.position(new LatLng(Double.parseDouble(arraylat[i]), Double.parseDouble(arraylong[i])));
                		markeropt.title(""+arraynombre[i].toString());
                		markeropt.snippet(""+arraydireccion[i].toString());
                		
                		
                		markeropt.icon(BitmapDescriptorFactory.fromResource(resource));
//                		Marker marker = new Marker(markeropt);
                		Marker marker = mMap.addMarker(markeropt);
                		marker.getId();
//                        .position(new LatLng(Double.parseDouble(arraylat[i]), Double.parseDouble(arraylong[i])))
//                        .title(arraynombre[i])
//                        .snippet(arraynombre[i])
//                        .icon(BitmapDescriptorFactory.fromResource(resource)));
//                		EventInfo eventInfo = new EventInfo(new LatLng(Double.parseDouble(arraylat[i]), 
//        						Double.parseDouble(arraylong[i])), 
//        						arraydireccion[i], arraynombre[i], arraypoid[i]);
//        				eventMarkerMap = new HashMap<Marker, EventInfo>();
//        				eventMarkerMap.put(marker, eventInfo);
            		}
            	
            	}
            	Criteria criteria = new Criteria();
                LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                String provider = locationManager.getBestProvider(criteria, false);
                Location location = locationManager.getLastKnownLocation(provider);
                double lat =  location.getLatitude();
                double lng = location.getLongitude();
                Log.i("LAT CENTER", lat+"");
                Log.i("LNG CENTER", lng+"");
                LatLng coordinate = new LatLng(lat, lng);

             // Move the camera instantly to Sydney with a zoom of 15.
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 10));

                // Zoom in, animating the camera.
                mMap.animateCamera(CameraUpdateFactory.zoomIn());

                // Zoom out to zoom level 10, animating with a duration of 2 seconds.
                mMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000,null);
//                LatLng coordinate = new LatLng(lat, lng);
//                mMap.set
                mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
					
					@Override
					public void onInfoWindowClick(Marker arg0) {
//						EventInfo eventInfo = eventMarkerMap.get(arg0);
						for(int i = 0; i < resultados.size(); i++){
							if(arg0.getTitle().trim().equals(arraynombre[i])){
								Toast.makeText(getApplicationContext(), "id "+arraypoid[i], Toast.LENGTH_LONG).show();
							}
						}
					}
				});
            }
        }
    }
		
	
}
